package com.example.demo.controller;

import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ling
 * Date: 2023-01-12
 * Time: 20:16
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;


    @RequestMapping("/add")
    public int add(String name,String password) {
        //1.非空校验
        if(!StringUtils.hasLength(name)||!StringUtils.hasLength(password)) {
            return 0;
        }
        //开启事务
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        int result = userService.add(name,password,null);
        System.out.println("添加影响行数:"+result);
        //提交事务或回滚事务
        dataSourceTransactionManager.commit(transactionStatus);
       // dataSourceTransactionManager.rollback(transactionStatus);
        return result;
    }
    @RequestMapping("/add2")
    @Transactional(propagation = Propagation.REQUIRED)
    public int add2(String name,String password) {
        //1.非空校验
        if(!StringUtils.hasLength(name)||!StringUtils.hasLength(password)) {
            return 0;
        }
        try {
            // 执⾏了异常代码(0不能做除数)

            int i = 10 / 0;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        int result = userService.add(name, password, null);
        System.out.println("添加影响行数：" + result);


        return result;
    }
}
